package sample;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClient {


    public void Client() {
        Socket socket = null;
        OutputStream os = null;
        FileInputStream fis = null;
        ByteArrayOutputStream baos = null;
        try {
            //1、获得IP，并放入创建的socket中
            InetAddress inet = InetAddress.getByName("localhost");
            socket = new Socket(inet, 8899);
            //2、获得输出流，往外传数据
            os = socket.getOutputStream();
            //3、使用输入流获取文件对象
            fis = new FileInputStream(new File("dataMonitoring.txt"));
            //4、字节流读取文件
            byte[] buffer = new byte[5];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                //4.1、使用socket的输出流写出文件
                os.write(buffer, 0, len);
            }
            socket.shutdownOutput();
            //5、接收来自服务端的数据，并显示到控制台上
            InputStream is = socket.getInputStream();
            baos = new ByteArrayOutputStream();
            byte[] buffer2 = new byte[5];
            int len2;
            while ((len2 = is.read(buffer2)) != -1) {
                baos.write(buffer2, 0, len2);
            }
            //显示接收到的数据
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        //6、资源关闭
        try {
            if (baos != null)
                baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (fis != null)
                fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (socket != null)
                socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
